<template>
  <div>
    <el-form ref="ruleForm" label-position="top" size="small" label-width="80px" class="base-search-more">
      <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <el-select style="width:90%" v-model="params.agentId" filterable clearable default-first-option placeholder="--区域--" @change="changeId">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属BD">
            <el-select style="width:90%" @change="getTableList()" :disabled="$store.state.type === 5" v-model="params.bdId" filterable clearable placeholder="--所属BD--">
              <el-option v-for="items in businessDevelopmentList" :key="'businessDevelopmentList'+items.id" :label="items.name" :value="items.id" />
            </el-select>
          </el-form-item>
        </el-col>
         <el-col :span="$store.state.showAgent? 12: 18">
          <el-form-item label-width="0">
            <div class="time-change">
              <el-radio-group style="margin-right: 10px;" v-model="params.type" size="small">
                <el-radio-button :label="1">日节点</el-radio-button>
                <el-radio-button :label="2">周节点</el-radio-button>
                <el-radio-button :label="3">月节点</el-radio-button>
              </el-radio-group>
              <div class="in-line">
                <pt-date-picker style="width: 300px" v-if="params.type === 1" v-model="params.date"
                    :shortcuts="[{ text: '今天', start: 0, end: 0},{ text: '近七天', start: -7, end: 0}, {text: '近一个月', start: -30, end: 0}]" />
                <span v-if="params.type === 2">
                  <el-date-picker style="width: 160px" v-model="params.date[0]" type="week" :clearable="false" 
                    format="yyyy 第 WW 周" value-format='yyyy-MM-dd HH:mm:ss' placeholder="选择周" 
                    :picker-options="{disabledDate: time => (time.getTime() > Date.now() || (params.date[1] ? time.getTime() > new Date(params.date[1]).getTime() : false))}"/> 至
                  <el-date-picker style="width: 160px" v-model="params.date[1]" type="week" :clearable="false"
                    :picker-options="{disabledDate: time => (time.getTime() > Date.now() || (params.date[0] ? time.getTime() < new Date(params.date[0]).getTime() : false))}"
                    format="yyyy 第 WW 周" value-format='yyyy-MM-dd HH:mm:ss' placeholder="选择周" />
                </span>
                <pt-date-picker style="width: 300px" v-if="params.type === 3" v-model="params.date"
                  type="monthrange" :shortcutsDiy="true" :shortcuts="shortcutsMonth" format='yyyy-MM' />
                <el-button style="margin-left: 10px;" type="primary" size="mini" @click="getTableList()">确认</el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
     <el-tabs v-model="pageIndex">
      <el-tab-pane label="数据概览" name="1">
        <div class="item-wrap">
          <div class="item" v-for="(item, index) in tableData.names1" :key="'totalSum' + index">
            <div class="head">{{item.name}}</div><div class="rice" :id="'totalSum' + index"></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="数据筛查" name="2">
        <div class="chock-item">
          <div class="left">选择指标</div>
          <el-checkbox-group v-model="checkboxGroup" size="mini" :max="2">
            <div class="item"><span class="name">交易</span>
              <span class="chek" v-for="(item, index) in tableData.names.filter(i => i.table === '交易')" :key="'names'+index">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
              </span>
            </div>
            <div class="item"><span class="name">供给</span>
              <span class="chek" v-for="(item, index) in tableData.names.filter(i => i.table === '供给')" :key="'names'+index">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
              </span>
            </div>
            <div class="item"><span class="name">用户</span>
              <span class="chek" v-for="(item, index) in tableData.names.filter(i => i.table === '用户')" :key="'names'+index">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
              </span>
            </div>
            <div class="item"><span class="name">履约</span>
              <span class="chek" v-for="(item, index) in tableData.names.filter(i => i.table === '履约')" :key="'names'+index">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
              </span>
            </div>
            <div class="item"><span class="name">补贴</span>
              <span class="chek" v-for="(item, index) in tableData.names.filter(i => i.table === '补贴')" :key="'names'+index">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
              </span>
              <el-button type="primary" size="mini" :disabled="checkboxGroup.length < 2" @click="drawSalePrice()">确认</el-button>
            </div>
            
          </el-checkbox-group>
        </div>
        <div id="salePrice"></div>
      </el-tab-pane>
      <el-tab-pane label="表格统计" name="3">
        <el-row type="flex" justify="end">
          <el-button @click="exportExcel()">导出表格<i class="el-icon-download"></i></el-button>
        </el-row>
        <div class="base-table-wrap">
         <el-table :data="tableData.item" max-height="600" :summary-method="getSummaries" show-summary id="out-table">
            <el-table-column prop="date" label="日期" min-width="100px" align="left" />
            <el-table-column v-for="(item, index) in tableData.names.filter(i => i.table !== '不展示')"
              :prop="item.mark" :key="'names' + index" :min-width="60 + item.name.length * 12 +'px'" align="right" >
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" :content="item.desc" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>{{item.name}}
              </template>
              <template slot-scope="scope">{{scope.row[item.mark]}}{{item.unit === '%' ? '%': ''}}</template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <pt-table-loading v-show="isloadingTable" />
  </div>
</template>
<script>
  var newDate = new Date()
  import { businessDevelopment } from '@/api/busnt.js'
  import { dataAnalysis } from '@/api/data.js'
  import { getDay } from '@/utils/ptkc.js'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  import acction from '@/utils/acction.js'
  import 'echarts/theme/macarons.js'
  export default {
    data() {
      return {
        shortcutsMonth: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()])
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(new Date().getFullYear(), 0)
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 6)
            picker.$emit('pick', [start, end])
          }
        }],
        params: {
          agentId: '', // 被选区域
          bdId: null,
          type: 1,
          date: []
        },
        isloadingTable: false,
        pageIndex: '1',
        businessDevelopmentList: [], // bd数据
        tableData: {
          names: [], // 帅选 选项
          names1: [], // 图形展示控制
          item:[] // 所有数据源
        },
        curParams: {}, // 请求数据的
        checkboxGroup: [], // 本地筛选数据对比
        myChart: null, // 数据分析
        isChangeWindow: false,
        chartList: [] // 
      }
    },
    computed: {
      restaurants() { // 区域据
        return this.$store.state.agentList
      }
    },
    watch: {
      restaurants: {
        handler(val) {
          if (val && val.length ===1) {
            this.params.agentId = val[0].id
          }
        },
        deep: true
      },
      'params.type': {
        handler(val) {
          if (val === 1) this.params.date = [getDay(-30) + ' ' + '00:00:00', getDay(0) + ' ' + '23:59:59']
          else if(val === 2) this.params.date = []
          else if(val === 3) this.params.date = []
        },
        deep: true,
        immediate: true
      },
      'params.agentId': {
        handler(val) {
          if (val) {
            this.getBusinessDevelopment(val)
          } else {
            this.businessDevelopmentList = []
          }
        },
        deep: true
      },
      pageIndex(val) { // 防止列表窗口变化导致变形
        if (val !== '3' && this.isChangeWindow) {
          this.$nextTick(() => {
            if (val === '1' && this.chartList.length) this.chartList.forEach(item => item.resize())
            else if (val === '2' && this.myChart) this.myChart.resize()
          })
        } 
      },
      '$store.state.screenRice': {
        handler(val) {
          if (this.myChart || this.chartList.length) {
            if (this.pageIndex === '1' && this.chartList.length) this.chartList.forEach(item => item.resize())
            else if (this.pageIndex === '2' && this.myChart) this.myChart.resize() 
            else this.isChangeWindow = true
          }
        },
        deep: true
      }
    },
    methods: {
      totalSumChart() { // 数据概览表
        this.tableData.names1.forEach((item, index) => {
          this.$nextTick(() => {
            this.chartList[index] = this.$echarts.init(document.getElementById('totalSum' + index), 'macarons')
            const unitIndex = this.tableData.names.findIndex(i => i.name === item.array[0])
            const unit = this.tableData.names[unitIndex].unit
            const color = ['#508df9','#ff967d', '#bb73cb', '#bad778']
            const donwColor = ['#fefcf6', '#fcfdf5', '#faf1f7', '#fdfffc']
            const series = item.array.map((list, lIndex) => {
              const nameIndex = this.tableData.names.findIndex(i => i.name === list)
              const key = this.tableData.names[nameIndex].mark
              const config = {
                name: list, type: index === 0 ? 'bar': 'line',
                smooth: true, lineStyle:{ width: 1 },
                data: this.tableData.item.map(i =>i[key])
              }
              if (index !== 0) {
                config.areaStyle = {
                  color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
                  colorStops: [{ offset: 0, color: color[lIndex] }, { offset: 1, color: donwColor[lIndex] }]}
                }
              } else {
                if (lIndex !== 0) config.stack = '商家'
              }
              return config
            })
            this.chartList[index].setOption({
              legend: { data: item.array },
              tooltip: { trigger: 'axis',axisPointer: { animation: false }, formatter: (params) => {
                let str = `<div><p>${params[0].name.split('[')[0]}</p></div>`
                for (let i = 0; i< params.length; i++) {
                  str += `${params[i].marker} ${params[i].seriesName}: ${params[i].data}${unit}<br />`
                }
                return str
              }},
              color: color,
              grid: { left: 70, top: 30, right: 70 }, // 距离容器上边像素
              xAxis: [{ 
                type: 'category', splitLine: { show: true }, boundaryGap: index === 0,
                axisLine:{ lineStyle:{ color:'#333', width: 1 }},
                data: this.tableData.item.map(item => item.date)
              }],
              yAxis: [{ type: 'value',axisLabel: { show: true, interval: 'auto', formatter: `{value}${unit}`}, axisLine: { lineStyle: { color:'#333', width: 1}}}],
              series:series
            })
          })
        })
      },
      drawSalePrice() { // 数据分析表
        if (this.checkboxGroup.length < 2) {
          this.$message.error('请选择需要对比的两组选项')
          return false
        }
        if (this.myChart) {
          this.myChart.clear()
          this.myChart = null
        }
        const rowIndex = this.checkboxGroup.map(i => this.tableData.names.findIndex(s => i === s.name))
        let yAxis = {}
        let yAxisIndex = null
        if (this.tableData.names[rowIndex[0]].unit !== this.tableData.names[rowIndex[1]].unit) {
          yAxis = [{ 
            type: 'value', name: this.tableData.names[rowIndex[0]].name, axisLabel: {show: true, interval: 'auto', formatter: `{value}${this.tableData.names[rowIndex[0]].unit}` }, 
            axisLine:{ lineStyle:{ color:'#333', width: 1 }} 
          },{ 
            type: 'value', name: this.tableData.names[rowIndex[1]].name, axisLabel: {show: true, interval: 'auto', formatter: `{value}${this.tableData.names[rowIndex[1]].unit}` }, 
            axisLine:{ lineStyle:{ color:'#333', width: 1 }} 
          }]
          yAxisIndex = 1
        } else {
          yAxis = [{ type: 'value',axisLabel: {show: true, interval: 'auto', formatter: `{value}${this.tableData.names[rowIndex[0]].unit}` }, axisLine:{ lineStyle:{ color:'#333', width: 1 }} }]
        }
        this.myChart = this.$echarts.init(document.getElementById('salePrice'), 'macarons')
        this.myChart.setOption({
          legend: { data: this.checkboxGroup },
          tooltip: { trigger: 'axis',axisPointer: { animation: false }, formatter: (params) => {
            let str = `<div><p>${params[0].name.split('[')[0]}</p></div>`
            for (let i = 0; i< params.length; i++) {
              str += `${params[i].marker} ${params[i].seriesName}: ${params[i].data}${this.tableData.names[rowIndex[i]].unit}<br />`
            }
            return str
          }},
          color: ['#649af9', '#fdd182'],
          grid: { left: 70, top: 30, right: 70 }, // 距离容器上边像素
          xAxis: [{ 
            type: 'category', splitLine: { show: true }, boundaryGap: false,
            axisLine:{ lineStyle:{ color:'#333', width: 1 }},
            data: this.tableData.item.map(item => item.date)
          }],
          yAxis: yAxis,
          series:[{ 
            name: this.checkboxGroup[0], type:'line', smooth: true, areaStyle: {
            color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#649af9' }, { offset: 1, color: '#e7eefb' }],
            }}, data: this.tableData.item.map(i =>i[this.tableData.names[rowIndex[0]].mark]), lineStyle:{ width: 1 }
          },{
            name: this.checkboxGroup[1], type:'line', smooth: true,  areaStyle: {
            color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#fdd182' }, { offset: 1, color: '#f9f4eb' }],
            }}, data: this.tableData.item.map(i =>i[this.tableData.names[rowIndex[1]].mark]), lineStyle:{ width: 1 }, yAxisIndex
          }]
        })
      },
      getSummaries(param) { // 表单总计
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
            return
          }
          const unitIndex = this.tableData.names.findIndex(i => i.mark === column.property)
          if (this.tableData.names[unitIndex].summary === 'false') {
            sums[index] = 'N/A'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value))  return new acction(prev,curr).accAdd()
              else return prev
            }, 0)
          } else {
            sums[index] = 'N/A'
          }
        })
        return sums
      },
      exportExcel() { // 下载表格
        const wb = XLSX.utils.table_to_book(document.querySelector('#out-table')) /* generate workbook object from table */
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'}) /* get binary string as output */
        const date = this.curParams.type === 1? '日' : this.curParams.type === 2? '周': this.curParams.type === 3 ? '月': ''
        const str = `${this.curParams.startTime.slice(0, 10)} - ${this.curParams.endTime.slice(0, 10)}${date}数据统计.xls`
        try {
          FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), str)
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      },
      getBusinessDevelopment(agentId) { // 获取BD数据
        businessDevelopment({ agentId }).then(res => {
          if (res.success) {
            this.businessDevelopmentList = res.data
            if (this.$store.state.type === 5) this.params.bdId = this.businessDevelopmentList[0].id || ''
          }
        })
      },
      changeId() { // 切换代理
        this.params.bdId = null
        this.getTableList()
      },
      getTableList() { // 数据分享
        const params = { ...this.params }
        if (params.date.length < 2) {
          this.$message.error('请选择时间')
          return false
        }
        params.startTime = params.date ? params.date[0] : ''
        params.endTime = params.date ? params.date[1] : ''
        delete params.date
        this.isloadingTable = true
        dataAnalysis(params).then(res => {
          if (res.success) {
            this.curParams = params
            this.tableData = res.data
            if (this.myChart) {
              this.myChart.clear()
              this.checkboxGroup = []
            }
            this.totalSumChart()
          }
        }).finally(() => { this.isloadingTable = false })
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length === 1) {
        this.params.agentId = this.restaurants[0].id
      }
      this.getTableList()
    }
  }
</script>
<style lang="scss" scoped>
  .item-wrap{
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    background: #fff;
    .item{
      width: 50%;
      height: 500px;
      box-sizing: border-box;
      .head{
        padding: 0 30px;
        height: 40px;
        font-size: 20px;
        font-weight: bold;
      }
      .rice{
        width: 100%;
        height: 450px;
      }
    }
  }
  .time-change {
    display: flex;
    flex-flow: column;
    .in-line{
      margin-top: 12px;
      display: flex;
      align-items: center;
    }
  }
  .chock-item{
    display: flex;
    .left{
      height: 30px;
      line-height: 30px;
      font-size: 16px;
    }
    .item {
      height: 30px;
      margin-bottom: 10px;
      .name{
        font-size: 12px;
        margin:0 20px; 
        padding:0 2px;
        border-radius: 2px;
        border: 1px solid #ccc;
      }
      .chek{
        line-height: 30px;
        margin-right: 20px;
      }
    }
  }
  #salePrice{
    margin-top: 50px;
    width: 100%;
    height: 450px;
  }
</style>
